import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
import store from '../store'
let apiUrl = window._CONFIG['domianURL'] || '/digital-village'
const fetchInstance = axios.create({
  //baseURL: process.env.VUE_APP_BASE_API,
  baseURL:apiUrl,
  timeout: 5000,
})


//request拦截器
fetchInstance.interceptors.request.use(config => {
  const token = getToken()
  if (token) {
    config.headers[ 'X-Access-Token' ] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  config.withCredentials = true
  return config
}, error => {
  console.log(error) // for debug
  return Promise.reject(error)
})

fetchInstance.interceptors.response.use(
  response => {
    const res = response.data
    switch(res.code){
      case 500:
        Message({message: res.message,type: 'error',duration: 2 * 1000})
        break
    }
    // const res = response.data
    // if (res.code !== 200) {
    //   console.log("response拦截器2")
    //   Message({
    //     message: res.message,
    //     type: 'error',
    //     duration: 5 * 1000
    //   })
    // } else {
    //   console.log("response拦截器4")
      
    // }
    return response.data
  }, error=> {
    console.log('err:', error.response)// for debug
    let data =  error.response.data
    let status = error.response.status
    const token = getToken()
    switch (status) {
      case 500:
        if(token && data.message=="Token失效，请重新登录"){
          Message({
            message: data.message,
            type: 'error',
            duration: 2 * 1000,
            onClose:()=>{
              store.dispatch('user/FedLogOut').then(() => {
                window.location.reload()
              })
            }
          })
        }else {
          Message({
            message: data.message,
            type: 'error',
            duration: 2 * 1000
          })
        }
        break
    }
    // Raven.captureException(error)
    return Promise.reject(error)
  }
)

export default fetchInstance
